#! /usr/bin/python

# @file print-s-cscf-configuration
#
# Copyright (C) Metaswitch Networks 2017
# If license terms are provided to you in a COPYING file in the root directory
# of the source code repository by which you are accessing this code, then
# the license outlined in that COPYING file applies to your use.
# Otherwise no rights are granted except for those provided to you by
# Metaswitch Networks in a separate written agreement.

import json, sys
from textwrap import dedent

# Expected format for the S-CSCF file
EXPECTED_FORMAT = dedent("""The expected format is:\n\
{
\"s-cscfs\" :
 [
   {
     \"server\" : \"<S-CSCF URI>\",
     \"priority\" : <priority>,
     \"weight\" : <weight>,
     \"capabilities\" : [<comma separated capabilities>],
   },
   ...
 ]
}""")

source = sys.argv[1] if len(sys.argv) > 1 else "/etc/clearwater/s-cscf.json"

# This does some basic validation of the S-CSCF configuration file, and
# prints the contents
try:
    with open(source) as scscf_file:
        try:
            scscf_data = json.load(scscf_file)
            scscfs = scscf_data["s-cscfs"]

            if scscfs:
                try:
                    for scscf in scscfs:
                        server = scscf["server"]
                        priority = scscf["priority"]
                        weight = scscf["weight"]
                        capabilities = scscf["capabilities"]

                        print "  Server: {}".format(server)
                        print "  Priority: {}".format(priority)
                        print "  Weight: {}".format(weight)
                        print "  Capabilities: {}".format(capabilities)
                        print ""

                except KeyError as e:
                    print "Invalid S-CSCF entry detected in file.\n"
                    print EXPECTED_FORMAT

            else:
                print "Configuration file is present, but contains no entries.\n"
                print EXPECTED_FORMAT

        except ValueError, KeyError:
            print "\nInvalid S-CSCF file at %s\n" % source
            print EXPECTED_FORMAT

except IOError:
    print "\nNo S-CSCF file at %s\n" % source
